#include "bluetoothclient.h"

#include <qbluetoothsocket.h>

BluetoothClient::BluetoothClient() {
    connect(&serviceManager, SIGNAL(singleServiceInstance()), this, SLOT(serviceReady()));
    connect(&serviceManager, SIGNAL(noServiceFound()), this, SIGNAL(noServiceFound()));
}

BluetoothClient::~BluetoothClient() {
    stopClient();
}

void BluetoothClient::startClient(const QBluetoothServiceInfo &remoteService) {
    qDebug() << "[BluetoothClient] Starting client...";

     // Connect to service
     socket = new QBluetoothSocket(QBluetoothSocket::L2capSocket);
     qDebug() << "Create socket";
     socket->connectToService(remoteService);
     qDebug() << "ConnecttoService done";

     connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
     connect(socket, SIGNAL(connected()), this, SLOT(connected()));
     connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
}

void BluetoothClient::stopClient() {
    qDebug() << "[BluetoothClient] Stopping client...";
    socket->deleteLater();
}

void BluetoothClient::sendMessage(const QString &message) {
    QByteArray text = message.toUtf8() + '\n';
    socket->write(text);
}

void BluetoothClient::readSocket() {
    if (!socket)
        return;

     while (socket->canReadLine()) {
         QByteArray line = socket->readLine();
         emit messageReceived(line);
     }
}

void BluetoothClient::connected() {
    qDebug() << "[BluetoothClient] Connected!";
    sendMessage("Hello");

    emit socketConnected(socket);
}

void BluetoothClient::discoverService() {
    serviceManager.startDiscovery();
}

void BluetoothClient::serviceReady() {
    QBluetoothServiceInfo service = serviceManager.service();
    startClient(service);
}

void BluetoothClient::disconnected() {
    qDebug() << "[BluetoothClient] Disconnected!";
    emit socketDisconnected();
}
